from flask import Flask, json,request,jsonify
# 实现orm，对象关系映射
from flask_sqlalchemy import SQLAlchemy
import sqlalchemy
from config import Config
from flask_cors import CORS
import json

app = Flask(__name__)
db = SQLAlchemy(app)
CORS(app)
app.config.from_object(Config)
# 创建分类表
class Cate(db.Model):
    __tablename__='cate'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(20),unique=True)
    level = db.Column(db.Integer,default=1)
    pid = db.Column(db.Integer,default=0)
# db.create_all()

@app.route('/cateM',methods = ['POST','GET','DELETE','PUT'])
def cateM():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        cate = Cate(name = data['name'])
        db.session.add(cate)
        db.session.commit()
        return jsonify({'code':200})
    elif request.method=='GET':
        cates = Cate.query.all()
        list =[]
        for i in cates:
            dict = {'id':i.id,'name':i.name}
            list.append(dict)
        return jsonify({'code':200,'list':list})
    elif request.method=='DELETE':
        id = request.args.get('id')
        Cate.query.filter_by(id=id).delete()
        db.session.commit()
        return jsonify({"code":200})
    else:
        id = request.args.get('id')
        Cate.query.filter_by(id=id).update({'name':'汽车类'})
        db.session.commit()
        return jsonify({"code":200})

if __name__ == '__main__':
    app.run(debug=True)
    